<?php

namespace App\Models;


use App\Libs\DataFormat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class Feeling extends Model
{
    use DataFormat;

    protected  $table='feeling_tone';

    protected  $guarded = ['id', 'created_at'];

    protected $casts = ['photo'=>'array'];

    protected  $withCount;

    public static  $formatKey = ['id'=>'int', 'type'=>'int', 'content'=>'string', 'photo'=>'json_decode', 'like_count'=>'int', 'comment_count'=>'int' ];

    public function user()
    {
        return $this->hasOne('App\Models\User', 'id', 'user_id');
    }

    public function team()
    {
        return $this->hasOne('App\Models\Team', 'id', 'relation_id');
    }

    public function project()
    {
        return $this->hasOne('App\Models\Project', 'id', 'relation_id');
    }

    public function getAllInfo($userId = 0)
    {
        $data = Feeling::format($this);

        $data['user_info'] = $this->user->getAllInfo();

        switch ($this->type)
        {
            case 2:
                $data['project_info'] = Project::format($this->project);
                break;

            case 3:
                $data['team_info'] = Team::format($this->team);
                break;

        }

        $time = time() - strtotime($this->created_at);
        if($time <= 0)
        {
            $create = '1分钟前';
        } elseif($time < 3600)
        {
            $create = ceil($time/60).'分钟前';
        }elseif($time < 86400)
        {
            $create = round($time / 3600).'小时前';
        }else{
            $create = date('Y-m-d', strtotime($this->created_at));
        }

        $data['created_at'] = $create;

        $likes = User::whereRaw("id in (select user_id from feeling_tone_like where feeling_id={$this->id})")->orderBy('id')->get();

        $likeList = [];
        $data['is_like'] = 0;
        foreach($likes as $value)
        {
            $likeList[] = $value->getUserAvatar();
            if($value->id == $userId)
            {
                $data['is_like'] = 1;
            }
        }
        $data['like_list'] = $likeList;

        $comments = FeelingComment::where('feeling_id', $this->id)->orderby('id')->get();
        $commentList = [];
        foreach($comments as $value)
        {
            $commentList[] = $value->getAllInfo();
        }
        $data['comment_list'] = $commentList;


        return $data;
    }

    public function syncLikeCount()
    {
        $ct  = DB::table('feeling_tone_like')->where('feeling_id', $this->id)->count();

        $this->like_count = $ct;

        return $this->save();
    }

    public function syncCommentCount()
    {
        $ct  = DB::table('feeling_tone_comment')->where('feeling_id', $this->id)->where('is_display', 1)->count();

        $this->comment_count = $ct;

        return $this->save();
    }
}
